/**
 * 签包任务管理管理初始化
 */
var SignTasks = {
    id: "SignTasksTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1,
    isAdmin: false,
    sortValue: 1,
    status: 0,
    signBeginTime: null,
    signEndTime:null,
    merchantName: null
};

/**
 * 初始化表格的列
 */
SignTasks.initColumn = function () {
    return [[
        {
            title: 'App名称',
            field: 'appName',
            align: 'center',
            width: 180
        },
        {
            title: '设备号',
            field: 'deviceUdid',
            align: 'center'
        },
        {
            title: '签包时间',
            field: 'signTime',
            align: 'center',
            width: 180
        },
        {
            title: '签包状态',
            field: 'status',
            align: 'center',
            width:100,
            templet:function (res) {
                //0 待签 1 签包中 2 签包成功 3 添加设备失败 4 签包失败(添加设备成功)
                if (res.status === 0){
                    return "待签包"
                }
                else if (res.status === 1){
                    return "签包中"
                }
                else if (res.status === 2){
                    return "签包成功"
                }
                else if (res.status === 3){
                    return "添加设备失败"
                }
                else if (res.status === 4){
                    return "签包失败（添加设备成功）"
                }
            }
        }

    ]];
};

/**
 * 管理员身份查看的表单项
 * @returns {({field: string, width: number, style: string, title: string, align: string}|{field: string, width: number, title: string, align: string}|{field: string, width: number, title: string, align: string}|{field: string, width: number, title: string, align: string}|{field: string, templet: templet, width: number, title: string, align: string})[][]}
 */
SignTasks.adminColumn = function () {
    return [[
        {
            title: 'App名称',
            field: 'appName',
            align: 'center',
            width: 200
        },
        {
            title: '商户名称',
            field: 'merchant',
            align: 'center',
            width: 100
        },
        {
            title: '设备号',
            field: 'deviceUdid',
            align: 'center'
        },
        {
            title: '苹果账号',
            field: 'appleAccount',
            align: 'center'
        },
        {
            title: '签包时间',
            field: 'signTime',
            align: 'center',
            width: 180
        },
        {
            title: '签包状态',
            field: 'status',
            align: 'center',
            width:100,
            templet:function (res) {
                //0 待签 1 签包中 2 签包成功 3 添加设备失败 4 签包失败(添加设备成功)
                if (res.status === 0){
                    return "待签包"
                }
                else if (res.status === 1){
                    return "签包中"
                }
                else if (res.status === 2){
                    return "签包成功"
                }
                else if (res.status === 3){
                    return "添加设备失败"
                }
                else if (res.status === 4){
                    return "签包失败（添加设备成功）"
                }
            }
        }

    ]];
};

SignTasks.tableList = function (queryData) {
    layui.use("table", function () {
        var table = layui.table;

        SignTasks.table = table;

        table.render({
            elem: "#table",
            url: Feng.ctxPath + "/signTasks/list",
            cellMinWidth: 120,
            where: queryData,
            page: true,
            limit: 20,
            cols: SignTasks.isAdmin?SignTasks.adminColumn():SignTasks.initColumn(),
            parseData: function (res) {
                return {
                    "code": 0,
                    "msg": "获取成功",
                    "count": res.total,
                    "data": res.items
                }
            },
            text: {
                none: '暂无相关数据'
            },
            id: "tableReload"
        });
    });
};
/**
 * 排序筛选
 */
SignTasks.changeSort = function(){
    SignTasks.sortValue = $("#sortCondition").val();

    SignTasks.table.reload("tableReload",{
        page: {
            curr: 1 //重新从第1页开始
        },
        where: getFilter()
    });
}

function getFilter(){
    var queryData = {};

    queryData['sortValue'] = SignTasks.sortValue;
    queryData['status'] = SignTasks.status;
    queryData['signBeginTime'] = SignTasks.signBeginTime;
    queryData['signEndTime'] = SignTasks.signEndTime;
    queryData['merchantName'] = SignTasks.merchantName;
    return queryData;
}

SignTasks.filterDetail = function(){
    SignTasks.status = $("#status").val();
    SignTasks.signBeginTime = $("#signBeginTime").val();
    SignTasks.signEndTime = $("#signEndTime").val();
    SignTasks.merchantName = $("#merchantName").val();

    SignTasks.table.reload("tableReload",{
        page: {
            curr: 1 //重新从第1页开始
        },
        where: getFilter()
    });
}

/**
 * 获取设备总量信息
 */
SignTasks.getDeviceInfoOfApp = function(){
    var queryData = {};
    queryData['beginTime'] = $("#beginTime").val();
    queryData['endTime'] = $("#endTime").val();
    let ajax = new $ax(Feng.ctxPath + "/signTasks/deviceInfo", function (data) {
        $("#useDeviceCount").text(data.deviceCount);
        $("#appCount").text(data.appCount);
        $("#buyDeviceCount").text(data.buyDeviceCount);
        $("#remainingCount").text(data.remainingCount)
    }, function (data) {
        Feng.error("获取信息失败!");
    });
    ajax.async = true;
    ajax.set(queryData);
    ajax.start();
}
/**
 * 获取每日设备信息图表数据
 */
SignTasks.getDeviceInfoObBar = function(){
    var queryData = {};

    if (SignTasks.isAdmin){
        queryData['merchantId'] = $("#selectMerchantName").val();
    }
    queryData['beginTime'] = $("#beginTime").val();
    queryData['endTime'] = $("#endTime").val();
    let ajax = new $ax(Feng.ctxPath + "/signTasks/everyDayDeviceInfo", function (data) {
        SignTasks.showDeviceInfo(data);
    }, function (data) {
        Feng.error("获取信息失败!"+data.responseJSON.message);
    });
    ajax.async = true;
    ajax.set(queryData);
    ajax.start();
}

SignTasks.showDeviceInfo = function(deviceInfo){
    const dom = document.getElementById("deviceInfo");
    const myChart = echarts.init(dom);
    const option = {
        title: {
            text: '每日签包设备数',
            left: 'center'
        },
        yAxis: {
            type: 'value'
        },
        xAxis: {
            type: 'category',
            data: deviceInfo.signTimeArr,
            axisLabel:{
                interval: 0,
                rotate: -45
            }
        },
        series: [
            {
                type: 'bar',
                data: deviceInfo.deviceCountArr,
                itemStyle: {//系列级个性化
                    normal: {
                        color: "#2d8ffd",
                        label:{
                            show:true,
                            position : 'top',
                            formatter : function (params) {
                                return params.value
                            },
                            textStyle:{
                                fontSize:14
                            }
                        },
                    }
                },
                barWidth: 30
            }
        ]
    };

    if (option && typeof option === "object") {
        myChart.setOption(option, true);
    }
}

/**
 * 获取商户安装设备信息
 */
SignTasks.getMerchantDeviceInfo = function(){
    var queryData = {};
    queryData['merchantId'] = $("#appName").val();
    queryData['beginTime'] = $("#beginTime").val();
    queryData['endTime'] = $("#endTime").val();
    let ajax = new $ax(Feng.ctxPath + "/signTasks/getMerchantDeviceInfo", function (data) {
        SignTasks.showMerchantUsedPie(data.usedBO);
        SignTasks.showMerchantBuyPie(data.buyBO);
        SignTasks.showMerchantRemainingPie(data.remainingBO);
    }, function (data) {
        Feng.error("获取信息失败!");
    });
    ajax.async = true;
    ajax.set(queryData);
    ajax.start();
}
/**
 * 商户已使用的饼状图
 * @param res
 */
SignTasks.showMerchantUsedPie = function(res){
    const dom = document.getElementById("merchantDeviceUsed");
    const myChart = echarts.init(dom);
    const option = {
        series: [
            {
                type: 'pie',
                radius: '55%',
                data: SignTasks.merchantData(res)
            }
        ]
    };

    if (option && typeof option === "object") {
        myChart.setOption(option, true);
    }
}

/**
 * 商户购买数量饼状图
 * @param res
 */
SignTasks.showMerchantBuyPie = function(res){
    const dom = document.getElementById("merchantDeviceBuy");
    const myChart = echarts.init(dom);
    const option = {
        series: [
            {
                type: 'pie',
                radius: '55%',
                data: SignTasks.merchantData(res)
            }
        ]
    };

    if (option && typeof option === "object") {
        myChart.setOption(option, true);
    }
}

/**
 * 商户剩余设备饼图
 * @param res
 */
SignTasks.showMerchantRemainingPie = function(res){
    const dom = document.getElementById("merchantDeviceRemaining");
    const myChart = echarts.init(dom);
    const option = {
        series: [
            {
                type: 'pie',
                radius: '55%',
                data: SignTasks.merchantData(res)
            }
        ]
    };

    if (option && typeof option === "object") {
        myChart.setOption(option, true);
    }
}

SignTasks.merchantData = function(res){
    let data = [];
    let len = res.length;
    for (let i = 0; i < len; i++) {
        data.push({value: res[i].deviceCount, name: res[i].merchantName,label:{
                show: true,
                formatter: function(params){
                    return params.name + "\n"+params.value
                }
            }})
    }
    return data;
}
/**
 * 查询签包设备统计数据
 */
SignTasks.querySignInfo = function(){
    // if (SignTasks.isAdmin){
    //     SignTasks.getMerchantDeviceInfo();
    // }

    // SignTasks.getDeviceInfoOfApp();
    SignTasks.getDeviceInfoObBar();
}

/**
 * 获取商户列表
 */
SignTasks.getMerchantList = function(){
    let ajax = new $ax(Feng.ctxPath + "/signTasks/merchantList", function (data) {
        data.forEach(function (item) {
            $("#selectMerchantName").append("'<option value='"+item.id+"'>"+item.name+"</option>'");
            $("#merchantName").append("'<option value='"+item.id+"'>"+item.name+"</option>'");
        }) ;
    }, function (data) {
        Feng.error("获取商户列表失败");
    });
    ajax.async = true;
    ajax.start();
}

$(function () {
    if ($("#isAdmin").val() == "超级管理员"){
        SignTasks.isAdmin = true;
        SignTasks.getMerchantList();
        SignTasks.getMerchantDeviceInfo();
    }else{
        SignTasks.isAdmin = false;
    }

    SignTasks.getDeviceInfoOfApp();
    SignTasks.querySignInfo();

    SignTasks.tableList();
});
